﻿using CookieLogin.Entity;
using CookieLogin.Repository;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;


namespace CookieLogin.Controllers
{
    public class UserLogin : Controller
    {

        private readonly UserRepository _userRepository;

        public UserLogin(UserRepository userRepository)
        {
            _userRepository = userRepository;
        }


        [HttpGet]
        public IActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Login(User user)
        {

            if (!ModelState.IsValid)
            {
                return View();
            }


            User userModel = _userRepository.GetBy(user.UserName);

            if (userModel == null)
            {
                ModelState.AddModelError("UserName", "用户名不存在!");
                return View();
            }

            if (userModel.Password != user.Password)
            {
                ModelState.AddModelError("Password", "用户名或者密码不正确!");
                return View();
            }


            CookieOptions options = new CookieOptions()
            {
                Expires = DateTimeOffset.Now.AddDays(7)
            };


            Response.Cookies.Append("UserId", userModel.Id.ToString(), options);


            return View();
        }


        [HttpGet]
        public IActionResult Register()
        {
            return View();
        }
    }
}
